package com.yugu.park.security.service;

import cn.hutool.core.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yugu.park.exception.BusinessException;
import com.yugu.park.security.entity.LoginUser;
import com.yugu.park.security.entity.TSysUser;

import javax.annotation.Resource;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

	@Resource
	private TSysUserService sysUserService;

//	@Resource
//	private SysPermissionService sysPermissionService;

	@Override
	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		TSysUser user = sysUserService.selectUserByUserName(username);
		if (ObjectUtil.isNull(user)) {
			log.info("登录用户：{} 不存在.", username);
			throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
		} else if (user.getDelFlag()!=null&&user.getDelFlag() == 1) {
			log.info("登录用户：{} 已被删除.", username);
			throw new BusinessException("对不起，您的账号：" + username + " 已被删除");
		} else if ("1".equals(user.getStatus())) {
			log.info("登录用户：{} 已被停用.", username);
			throw new BusinessException("对不起，您的账号：" + username + " 已停用");
		}

		return createLoginUser(user);
	}

	public UserDetails createLoginUser(TSysUser sysUser) {
//		List<String> permission = sysPermissionService.getPermission(sysUser);
		return new LoginUser(sysUser, null);
	}
}
